package iblink.event;

import packutil.event.AEvent;

public class IBErrorEvent extends AEvent {

	public static enum IbErrorType {
		CantConnectToTws, HistoricalDataServiceError, HistoricalDataPacingViolation, HistoricalDataNoPermissions, NoSecurityDefinitionFound, LostConnectivityToIB, ContractDescriptionAmbiguous, Unknown
	}

	private final int errorCode;

	private final IbErrorType errorType;

	private final String errorString;

	public IBErrorEvent(int eventId, int errorCode, String errorString) {
		super(eventId);
		this.errorCode = errorCode;
		this.errorType = mapError(errorCode, errorString);
		this.errorString = errorString;
	}

	public String toString() {
		return getClass().getSimpleName() + "[errorCode[" + errorCode
				+ "] errorType[" + errorType + "] errorString[" + errorString
				+ "]]";
	}

	private static IbErrorType mapError(int errorCode, String errorString) {

		switch (errorCode) {
		case (162):
			if (errorString
					.contains("Historical data request pacing violation"))
				return IbErrorType.HistoricalDataPacingViolation;
			if (errorString.contains("No market data permissions"))
				return IbErrorType.HistoricalDataNoPermissions;
			return IbErrorType.HistoricalDataServiceError;
		case (200):
			if (errorString.contains("The contract description specified for")
					|| errorString.contains("is ambiguous"))
				return IbErrorType.ContractDescriptionAmbiguous;
			return IbErrorType.NoSecurityDefinitionFound;
		case (502):
			return IbErrorType.CantConnectToTws;
		case (1100):
			return IbErrorType.LostConnectivityToIB;
		}

		return IbErrorType.Unknown;
	}

	public IbErrorType getErrorType() {
		return errorType;
	}

	public String getErrorString() {
		return errorString;
	}

	public int getErrorCode() {
		return errorCode;
	}
}